/* eslint-disable no-undef */
import React, {useState, useEffect} from 'react';
import {Keyboard} from 'react-native';
import {Text, View, Colors, TouchableOpacity} from 'react-native-ui-lib';
import AntdIcons from 'react-native-vector-icons/AntDesign';
import {useNavigation} from '@react-navigation/native';

let Mheader = ({title, style = {}, extraContent, contentWidth}) => {
  const navigation = useNavigation();
  const [isKeyboardVisible, setKeyboardVisible] = useState(false);

  useEffect(() => {
    // 添加键盘显示事件监听器
    const keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      () => {
        setKeyboardVisible(true);
      },
    );

    // 添加键盘隐藏事件监听器
    const keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      () => {
        setKeyboardVisible(false);
      },
    );

    // 在组件卸载时移除监听器
    return () => {
      keyboardDidShowListener.remove();
      keyboardDidHideListener.remove();
    };
  }, []);

  return (
    <View row paddingH-12 style={{...style}} spread center height={42}>
      <TouchableOpacity
        onPress={async () => {
          if (isKeyboardVisible) {
            Keyboard.dismiss();
            setTimeout(() => {
              navigation.goBack();
            }, 100);
          } else {
            navigation.goBack();
          }
        }}>
        <View row width={contentWidth ?? 60} left centerV height={42}>
          <AntdIcons
            name={'left'}
            size={20}
            style={{color: Colors.colorTextBase}}
          />
        </View>
      </TouchableOpacity>

      <View row flex-1 center>
        <Text heading>{title}</Text>
      </View>
      <View row width={contentWidth ?? 60} right>
        {typeof extraContent === 'function' ? extraContent() : extraContent}
      </View>
    </View>
  );
};

export default Mheader;
